import { ElMessage } from 'element-plus'
import { uploadInChunks } from '@/utils/file/upload'
import { enforceFileValidation, type FileRules } from '@/utils/file/validate'

export const uploadActions = {
  async uploadFileInChunks(this: any, file: File, remark?: string, options?: { chunkSize?: number; rules?: FileRules; module?: string }) {
    const CHUNK_SIZE = options?.chunkSize ?? (2 * 1024 * 1024)
    const chunkSize = Number(CHUNK_SIZE) > 0 ? Number(CHUNK_SIZE) : 2 * 1024 * 1024
    this.submitting = true
    this.progress = 0
    this.error = null
    try {
      // 上传前规则校验（类型/大小/扩展名）
      enforceFileValidation(file, options?.rules)
      // console.log('上传文件2：', file)
      const res = await uploadInChunks(file, {
        chunkSize,
        indexBase: 0,
        module: options?.module ?? 'null',
        onProgress: (p) => { this.progress = p },
        maxRetriesPerChunk: 2,
      })
      this.lastUpload = res.response
      ElMessage.success('文件上传成功')
      return res.response
    } catch (e: any) {
      this.error = e?.message || '上传失败'
      ElMessage.error(this.error ?? '上传失败')
      throw e
    } finally {
      this.submitting = false
    }
  },
}
